package jee.boot.module.iexp.task.impl;

import jee.boot.common.basic.ServiceException;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.remote.RemoteEndpoint;
import jee.boot.common.standard.AccountHandler;
import jee.boot.common.standard.AuthorityHandler;
import jee.boot.common.standard.DocumentStorageClient;
import jee.boot.common.utils.SpringContextHolder;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.task.IexpTaskConfig;
import jee.boot.entity.task.IexpTask;
import jee.boot.module.iexp.service.IexpTaskService;
import jee.boot.entity.task.StandardAsynchronousTaskService;
import jee.boot.module.iexp.task.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;

/**
 * 标准后台任务运行线程
 */
public class StandardRunnable extends BasicTaskRunnable implements Runnable {
    private Logger logger = LoggerFactory.getLogger(TaskListener.class);

    public StandardRunnable(IexpTask task, IexpTaskService iexpTaskService, DocumentStorageClient fileService, AuthorityHandler authorityHandler, AccountHandler accountHandler, RemoteEndpoint remoteEndpoint, ProjectConfig projectConfig) {
        this.task = task;
        this.iexpTaskService = iexpTaskService;
        this.fileService = fileService;
        super.authorityHandler = authorityHandler;
        super.accountHandler = accountHandler;
        super.remoteEndpoint=remoteEndpoint;
        super.projectConfig=projectConfig;
    }

    private IexpTaskService iexpTaskService;
    private IexpTask task;
    private DocumentStorageClient fileService;
    private AuthorityHandler authorityHandler;
    private AccountHandler accountHandler;

    @Override
    public void run() {
        logger.debug("后台标准任务[" + task.getName() + "(" + task.getId() + ")]开始执行");
//            if (task.getPriority() != 0) {
//                //线程优先级默认是5 设置区间1-10
////                Thread currentThread = Thread.currentThread();
////                currentThread.setPriority(task.getPriority());
//            }
        configThreadPermission(task);
        task.setStartDate(new Date());
        StandardAsynchronousTaskService service = null;
        try {
            String delegatedClass = task.getDelegatedClass();
            if (StringUtils.isBlank(delegatedClass)) {
                throw new Exception("委托服务类[delegatedClass]不能为空");
            }
            // 全路径,需要使用反射
            if (StringUtils.contains(delegatedClass, ".")) {
                Class<?> classService = Class.forName(delegatedClass);
                Object classObject = classService.newInstance();
                if (!(classObject instanceof StandardAsynchronousTaskService)) {
                    throw new Exception("委托服务类[delegatedClass]需要实现StandardAsynchronousTaskService接口");
                }
                service = (StandardAsynchronousTaskService) classObject;
            } else {
                Object classObject = SpringContextHolder.getBean(delegatedClass);
                if (!(classObject instanceof StandardAsynchronousTaskService)) {
                    throw new Exception("委托服务类[delegatedClass]需要实现StandardAsynchronousTaskService接口");
                }
                service = (StandardAsynchronousTaskService) classObject;
            }
            //前置处理
            service.preProcess(task);
            IexpTaskConfig config = service.taskConfig(task);
            //事务处理
            DataSourceTransactionManager dataSourceTransactionManager = SpringContextHolder.getBean(DataSourceTransactionManager.class);
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
            TransactionStatus transaction = dataSourceTransactionManager.getTransaction(def); // 获得事务状态
            try {
                service.execute(task);
                //提交事务
                dataSourceTransactionManager.commit(transaction);
                task.setIexpStatus("iexp_status_success");
                task.setMessage("success");
            } catch (Exception e) {
                task.setIexpStatus("iexp_status_error");
                logger.warn("存储数据异常，回滚业务数据");
                //事务回滚
                dataSourceTransactionManager.rollback(transaction);
                throw e;
            }
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            task.setMessage(getMessageCodeHelper().getMessage(e.getCode(),e.getData(),""));
            task.setIexpStatus("iexp_status_error");
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            task.setMessage(e.getMessage());
            task.setIexpStatus("iexp_status_error");
        }
        // 更新任务状态以及任务日志
        task.setEndDate(new Date());
        // 任务完成后置处理
        service.postProcess(task);
        iexpTaskService.update(task);
    }
}
